// 颜色工具包渲染器
window.ColorToolkitRenderer = class ColorToolkitRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="droplet" class="w-8 h-8 inline mr-3 text-pink-600"></i>
                颜色工具包
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">专业的颜色选择器、格式转换器和调色板生成器，支持HEX、RGB、HSL格式转换。</p>
            </div>
            
            <!-- 颜色选择器区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="eye" class="w-5 h-5 inline mr-2"></i>
                    颜色选择器
                </h3>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- 左侧：颜色输入和预览 -->
                    <div>
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">选择颜色</label>
                            <div class="flex items-center space-x-3">
                                <input 
                                    id="color-picker" 
                                    type="color" 
                                    value="#3B82F6"
                                    class="w-16 h-16 rounded-lg border-2 border-gray-300 cursor-pointer"
                                >
                                <div>
                                    <input 
                                        id="color-input" 
                                        type="text" 
                                        value="#3B82F6"
                                        placeholder="输入颜色值..."
                                        class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500 focus:border-transparent font-mono"
                                    >
                                    <p class="text-xs text-gray-500 mt-1">支持 HEX、RGB、HSL 格式</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 颜色预览 -->
                        <div id="color-preview" class="w-full h-24 rounded-lg border-2 border-gray-300 mb-4" style="background-color: #3B82F6;"></div>
                        
                        <!-- 随机颜色按钮 -->
                        <div class="flex flex-wrap gap-2">
                            <button 
                                id="random-color" 
                                class="bg-pink-600 hover:bg-pink-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                            >
                                <i data-feather="shuffle" class="w-4 h-4 mr-2"></i>
                                随机颜色
                            </button>
                            <button 
                                id="copy-current-color" 
                                class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                            >
                                <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                                复制
                            </button>
                        </div>
                    </div>
                    
                    <!-- 右侧：颜色格式显示 -->
                    <div id="color-formats" class="space-y-4">
                        <!-- 动态生成颜色格式 -->
                    </div>
                </div>
            </div>

            <!-- 颜色预设区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="grid" class="w-5 h-5 inline mr-2"></i>
                    颜色预设
                </h3>
                
                <div id="color-presets">
                    <!-- 动态生成颜色预设 -->
                </div>
            </div>

            <!-- 调色板生成器区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="layers" class="w-5 h-5 inline mr-2"></i>
                    调色板生成器
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">基础颜色</label>
                        <input 
                            id="palette-base-color" 
                            type="text" 
                            value="#3B82F6"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500 focus:border-transparent font-mono"
                        >
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">调色板类型</label>
                        <select 
                            id="palette-type" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
                        >
                            <option value="monochrome">单色调色板</option>
                            <option value="analogous">类似色</option>
                            <option value="complementary">补色</option>
                            <option value="triadic">三角色</option>
                            <option value="tetradic">四角色</option>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button 
                            id="generate-palette" 
                            class="w-full bg-pink-600 hover:bg-pink-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center justify-center"
                        >
                            <i data-feather="refresh-cw" class="w-4 h-4 mr-2"></i>
                            生成调色板
                        </button>
                    </div>
                </div>
                
                <!-- 调色板结果 -->
                <div id="palette-result" class="hidden">
                    <h4 class="font-medium text-gray-800 mb-3">生成的调色板</h4>
                    <div id="palette-colors" class="grid grid-cols-2 md:grid-cols-5 lg:grid-cols-9 gap-3">
                        <!-- 动态生成调色板 -->
                    </div>
                </div>
            </div>

            <!-- 颜色对比度检查器 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="activity" class="w-5 h-5 inline mr-2"></i>
                    对比度检查器
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">前景色</label>
                        <div class="flex items-center space-x-2">
                            <input 
                                id="contrast-fg-picker" 
                                type="color" 
                                value="#000000"
                                class="w-10 h-10 rounded border border-gray-300 cursor-pointer"
                            >
                            <input 
                                id="contrast-fg-input" 
                                type="text" 
                                value="#000000"
                                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500 font-mono text-sm"
                            >
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">背景色</label>
                        <div class="flex items-center space-x-2">
                            <input 
                                id="contrast-bg-picker" 
                                type="color" 
                                value="#FFFFFF"
                                class="w-10 h-10 rounded border border-gray-300 cursor-pointer"
                            >
                            <input 
                                id="contrast-bg-input" 
                                type="text" 
                                value="#FFFFFF"
                                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500 font-mono text-sm"
                            >
                        </div>
                    </div>
                    <div class="flex items-end">
                        <button 
                            id="check-contrast" 
                            class="w-full bg-pink-600 hover:bg-pink-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center justify-center"
                        >
                            <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                            检查对比度
                        </button>
                    </div>
                </div>
                
                <!-- 对比度预览 -->
                <div id="contrast-preview" class="mb-4">
                    <div class="p-6 rounded-lg border-2 border-gray-300 text-center" style="background-color: #FFFFFF; color: #000000;">
                        <h4 class="text-xl font-bold mb-2">示例文本 Sample Text</h4>
                        <p class="text-sm">这是用于测试对比度的示例文本，包含中文和English文字。</p>
                    </div>
                </div>
                
                <!-- 对比度结果 -->
                <div id="contrast-result" class="hidden">
                    <!-- 动态生成对比度结果 -->
                </div>
            </div>
        `;
    }

    static init() {
        // 颜色选择器相关元素
        const colorPicker = document.getElementById('color-picker');
        const colorInput = document.getElementById('color-input');
        const colorPreview = document.getElementById('color-preview');
        const randomColorBtn = document.getElementById('random-color');
        const copyColorBtn = document.getElementById('copy-current-color');
        
        // 调色板相关元素
        const paletteBaseColor = document.getElementById('palette-base-color');
        const paletteType = document.getElementById('palette-type');
        const generatePaletteBtn = document.getElementById('generate-palette');
        
        // 对比度检查相关元素
        const contrastFgPicker = document.getElementById('contrast-fg-picker');
        const contrastFgInput = document.getElementById('contrast-fg-input');
        const contrastBgPicker = document.getElementById('contrast-bg-picker');
        const contrastBgInput = document.getElementById('contrast-bg-input');
        const checkContrastBtn = document.getElementById('check-contrast');
        
        // 初始化
        this.loadColorPresets();
        this.updateColorFormats('#3B82F6');
        this.updatePaletteBaseColor('#3B82F6');
        
        // 颜色选择器事件
        colorPicker.addEventListener('input', (e) => {
            const color = e.target.value;
            colorInput.value = color.toUpperCase();
            this.updateColorDisplay(color);
        });
        
        colorInput.addEventListener('input', DevToolsUtils.debounce((e) => {
            const color = e.target.value.trim();
            if (color) {
                this.updateColorDisplay(color);
            }
        }, 300));
        
        // 随机颜色
        randomColorBtn.addEventListener('click', () => {
            const result = ColorToolkit.generateRandomColor();
            if (result.success) {
                const color = result.data.hex;
                this.updateColorDisplay(color);
            }
        });
        
        // 复制当前颜色
        copyColorBtn.addEventListener('click', () => {
            const color = colorInput.value;
            DevToolsUtils.copyToClipboard(color);
            DevToolsUtils.showToast('颜色已复制', 'success');
        });
        
        // 调色板生成
        paletteBaseColor.addEventListener('input', (e) => {
            this.updatePaletteBaseColor(e.target.value);
        });
        
        generatePaletteBtn.addEventListener('click', () => {
            this.generatePalette();
        });
        
        // 对比度检查器事件
        contrastFgPicker.addEventListener('input', (e) => {
            contrastFgInput.value = e.target.value.toUpperCase();
            this.updateContrastPreview();
        });
        
        contrastFgInput.addEventListener('input', (e) => {
            const color = e.target.value;
            if (this.isValidHexColor(color)) {
                contrastFgPicker.value = color;
                this.updateContrastPreview();
            }
        });
        
        contrastBgPicker.addEventListener('input', (e) => {
            contrastBgInput.value = e.target.value.toUpperCase();
            this.updateContrastPreview();
        });
        
        contrastBgInput.addEventListener('input', (e) => {
            const color = e.target.value;
            if (this.isValidHexColor(color)) {
                contrastBgPicker.value = color;
                this.updateContrastPreview();
            }
        });
        
        checkContrastBtn.addEventListener('click', () => {
            this.checkContrast();
        });
        
        // 初始化对比度预览
        this.updateContrastPreview();
        
        // 初始化 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }

    static updateColorDisplay(color) {
        const result = ColorToolkit.parseColor(color);
        
        if (result.success) {
            const { hex, rgb } = result.data;
            
            // 更新颜色选择器和输入框
            document.getElementById('color-picker').value = hex;
            document.getElementById('color-input').value = hex;
            document.getElementById('color-preview').style.backgroundColor = hex;
            
            // 更新颜色格式显示
            this.updateColorFormats(color);
            
            // 更新调色板基色
            document.getElementById('palette-base-color').value = hex;
        } else {
            DevToolsUtils.showToast(result.error, 'error');
        }
    }

    static updateColorFormats(color) {
        const result = ColorToolkit.parseColor(color);
        const formatsDiv = document.getElementById('color-formats');
        
        if (result.success) {
            const { hex, rgb, hsl } = result.data;
            
            formatsDiv.innerHTML = `
                <div class="space-y-3">
                    <div class="color-format-item border border-gray-200 rounded-lg p-3">
                        <div class="flex justify-between items-center">
                            <span class="font-medium text-gray-700">HEX</span>
                            <button class="copy-format-btn text-gray-400 hover:text-gray-600" data-value="${hex}">
                                <i data-feather="copy" class="w-4 h-4"></i>
                            </button>
                        </div>
                        <code class="text-lg font-mono text-gray-900">${hex}</code>
                    </div>
                    
                    <div class="color-format-item border border-gray-200 rounded-lg p-3">
                        <div class="flex justify-between items-center">
                            <span class="font-medium text-gray-700">RGB</span>
                            <button class="copy-format-btn text-gray-400 hover:text-gray-600" data-value="rgb(${rgb.r}, ${rgb.g}, ${rgb.b})">
                                <i data-feather="copy" class="w-4 h-4"></i>
                            </button>
                        </div>
                        <code class="text-lg font-mono text-gray-900">rgb(${rgb.r}, ${rgb.g}, ${rgb.b})</code>
                        <div class="text-sm text-gray-500 mt-1">R:${rgb.r} G:${rgb.g} B:${rgb.b}</div>
                    </div>
                    
                    ${hsl ? `
                    <div class="color-format-item border border-gray-200 rounded-lg p-3">
                        <div class="flex justify-between items-center">
                            <span class="font-medium text-gray-700">HSL</span>
                            <button class="copy-format-btn text-gray-400 hover:text-gray-600" data-value="hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)">
                                <i data-feather="copy" class="w-4 h-4"></i>
                            </button>
                        </div>
                        <code class="text-lg font-mono text-gray-900">hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)</code>
                        <div class="text-sm text-gray-500 mt-1">H:${hsl.h}° S:${hsl.s}% L:${hsl.l}%</div>
                    </div>
                    ` : ''}
                </div>
            `;
            
            // 绑定复制按钮事件
            document.querySelectorAll('.copy-format-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const value = e.currentTarget.getAttribute('data-value');
                    DevToolsUtils.copyToClipboard(value);
                    DevToolsUtils.showToast('格式已复制', 'success');
                });
            });
        } else {
            formatsDiv.innerHTML = `
                <div class="text-red-500 text-center py-4">
                    <i data-feather="alert-circle" class="w-8 h-8 mx-auto mb-2"></i>
                    <p>${result.error}</p>
                </div>
            `;
        }
        
        // 更新图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static loadColorPresets() {
        const result = ColorToolkit.getColorPresets();
        if (result.success) {
            const presetsDiv = document.getElementById('color-presets');
            let html = '';
            
            Object.entries(result.data).forEach(([categoryName, colors]) => {
                html += `
                    <div class="mb-4">
                        <h4 class="font-medium text-gray-800 mb-2">${categoryName}</h4>
                        <div class="grid grid-cols-6 md:grid-cols-12 lg:grid-cols-17 gap-2">
                            ${colors.map(color => `
                                <div class="preset-color-item w-10 h-10 rounded cursor-pointer border-2 border-gray-300 hover:border-gray-400 transition duration-200"
                                     style="background-color: ${color};"
                                     data-color="${color}"
                                     title="${color}">
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            });
            
            presetsDiv.innerHTML = html;
            
            // 绑定预设颜色点击事件
            document.querySelectorAll('.preset-color-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    const color = e.currentTarget.getAttribute('data-color');
                    this.updateColorDisplay(color);
                });
            });
        }
    }

    static updatePaletteBaseColor(color) {
        const result = ColorToolkit.parseColor(color);
        if (result.success) {
            document.getElementById('palette-base-color').value = result.data.hex;
        }
    }

    static generatePalette() {
        const baseColor = document.getElementById('palette-base-color').value;
        const type = document.getElementById('palette-type').value;
        
        const result = ColorToolkit.generatePalette(baseColor, type);
        const paletteResult = document.getElementById('palette-result');
        const paletteColors = document.getElementById('palette-colors');
        
        if (result.success) {
            const { palette } = result.data;
            
            paletteColors.innerHTML = palette.map(color => `
                <div class="palette-color-item text-center cursor-pointer group">
                    <div class="w-full h-16 rounded-lg border-2 border-gray-300 hover:border-gray-400 transition duration-200 mb-2"
                         style="background-color: ${color.hex};"
                         data-color="${color.hex}"
                         title="点击复制: ${color.hex}">
                    </div>
                    <div class="text-xs font-mono text-gray-600 group-hover:text-gray-800">${color.hex}</div>
                    <div class="text-xs text-gray-500">${color.name}</div>
                </div>
            `).join('');
            
            paletteResult.classList.remove('hidden');
            
            // 绑定调色板颜色点击事件
            document.querySelectorAll('.palette-color-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    const colorDiv = e.currentTarget.querySelector('[data-color]');
                    if (colorDiv) {
                        const color = colorDiv.getAttribute('data-color');
                        DevToolsUtils.copyToClipboard(color);
                        DevToolsUtils.showToast(`颜色 ${color} 已复制`, 'success');
                    }
                });
            });
            
            DevToolsUtils.showToast('调色板生成成功', 'success');
        } else {
            DevToolsUtils.showToast(result.error, 'error');
        }
    }

    static updateContrastPreview() {
        const fgColor = document.getElementById('contrast-fg-input').value;
        const bgColor = document.getElementById('contrast-bg-input').value;
        const preview = document.getElementById('contrast-preview').querySelector('div');
        
        preview.style.backgroundColor = bgColor;
        preview.style.color = fgColor;
    }

    static checkContrast() {
        const fgColor = document.getElementById('contrast-fg-input').value;
        const bgColor = document.getElementById('contrast-bg-input').value;
        
        const result = ColorToolkit.getColorContrast(fgColor, bgColor);
        const contrastResult = document.getElementById('contrast-result');
        
        if (result.success) {
            const { ratio, level, isAccessible } = result.data;
            
            contrastResult.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold ${isAccessible ? 'text-green-600' : 'text-red-600'}">${ratio}:1</div>
                        <div class="text-sm text-gray-600">对比度比例</div>
                    </div>
                    <div class="text-center">
                        <div class="text-xl font-bold ${isAccessible ? 'text-green-600' : 'text-red-600'}">${level}</div>
                        <div class="text-sm text-gray-600">无障碍等级</div>
                    </div>
                    <div class="text-center">
                        <div class="text-lg font-bold ${isAccessible ? 'text-green-600' : 'text-red-600'}">
                            ${isAccessible ? '✓ 通过' : '✗ 不通过'}
                        </div>
                        <div class="text-sm text-gray-600">WCAG 2.1标准</div>
                    </div>
                </div>
                
                <div class="mt-4 p-3 rounded-lg ${isAccessible ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}">
                    <div class="text-sm ${isAccessible ? 'text-green-800' : 'text-red-800'}">
                        ${isAccessible 
                            ? '✓ 此颜色组合符合WCAG无障碍访问标准，适合在网页中使用。'
                            : '⚠ 此颜色组合对比度不足，可能影响视觉障碍用户的阅读体验，建议调整颜色。'
                        }
                    </div>
                </div>
            `;
            
            contrastResult.classList.remove('hidden');
        } else {
            DevToolsUtils.showToast(result.error, 'error');
        }
    }

    static isValidHexColor(color) {
        return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color);
    }
};